﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.*;

	public class Blaze extends Sprite {
		private var sw:int;
		private var sh:int;
		private var level:int = 2;
		private var speed:int = -5;
		private var shape:Shape;
		private var cacheBmd:BitmapData;
		private var blazeMap:BitmapData;
		private var blazeBmd:BitmapData;
		private var blazeBmp:Bitmap;
		private var offset:Array = [];
		private var color:Array = [];
		private var df:DisplacementMapFilter;
		private var bf:BlurFilter;
		private var ct:ColorTransform;
		private var matrix:Matrix;

		public function Blaze() {
			sw = stage.stageWidth;
			sh = stage.stageHeight;
			//偏移
			for (var i:int = 0; i < level; i++) {
				offset[i] = new Point();
			}
			//火焰的渐变色
			for (var j:int = 0; j < 256; j++) {
				color.push(0xff0000);
			}

			//原始燃烧形状
			shape = new Shape();
			shape.graphics.lineStyle(2,0xff8000);
			shape.graphics.drawCircle(0,0,30);
			shape.x = sw * 0.5;
			shape.y = sh - 50;
			
			addChild(shape);
			
			cacheBmd = new BitmapData(sw,sh,true,0x00ff0000);
			blazeBmd = new BitmapData(sw,sh);
			blazeBmp = new Bitmap(blazeBmd);
			blazeMap = new BitmapData(sw,sh);
			addChild(blazeBmp);
			
			df  = new DisplacementMapFilter(blazeMap, new Point(), 1, 2, 5, 10,'clamp');
			bf = new BlurFilter(2,2,3);
			ct = new ColorTransform(0.95,0.95,0.95);
			
			//位置偏移
			matrix = new Matrix();
			matrix.tx = shape.x;
			matrix.ty = shape.y;
			
			addEventListener(Event.ENTER_FRAME, showBlaze);
		}

		private function showBlaze(e:Event) {
			for (var i:int = 0; i < level; i++) {
				offset[i].y += (i+1) * Math.abs(speed);
			}
			blazeMap.perlinNoise(25,25,level,Math.random(),false,true,3,false,offset);
			cacheBmd.scroll(0,speed);
			cacheBmd.colorTransform(cacheBmd.rect, ct);
			cacheBmd.draw(shape, matrix);
			cacheBmd.applyFilter(cacheBmd,cacheBmd.rect,new Point(),bf);
			cacheBmd.applyFilter(cacheBmd, cacheBmd.rect, new Point(), df);
			blazeBmd.paletteMap(cacheBmd, blazeBmd.rect, new Point(), color);

		}

	}
}